package band.wukong.practice.springboot.spring4.advanced.aware;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wukong(wukonggg@139.com)
 */
@Component
public class AwareService implements BeanNameAware, ResourceLoaderAware {

    private static final Logger logger = LoggerFactory.getLogger(AwareService.class);

    private String beanName;

    @Autowired
    private ResourceLoader loader;

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.loader = resourceLoader;
    }

    public void outputResult() {
        logger.info("Bean Name: " + beanName);
        final String PATH = "classpath:band/wukong/practice/springboot/spring4/advanced/aware/truth.txt";
        Resource resource = loader.getResource(PATH);
        try {
            logger.info("ResourceLoader 加载内容为：\n" + IOUtils.toString(resource.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

}
